<template>
    <div class="report-detail">
        <!-- <div class="page-header">
             <h1>报告详情</h1> 

    </div> -->

        <a-spin :spinning="loading">
            <a-row :gutter="24">
                <!-- 左侧：基本信息和封面图 -->
                <a-col :span="8">
                    <a-button @click="goBack">返回列表</a-button>
                    <a-card :bordered="true" style="margin-top: 20px;">
                        <div v-if="document">
                            <div class="cover-container" v-if="document.cover_image_url">
                                <img :src="document.cover_image_url" alt="报告封面" class="cover-image" />
                            </div>
                            <a-descriptions :column="1">
                                <a-descriptions-item label="报告名称">{{ document.file_name }}</a-descriptions-item>
                                <a-descriptions-item label="页数">{{ document.page_count }}</a-descriptions-item>
                                <a-descriptions-item label="解析状态">
                                    <a-tag v-if="document.parsing_status === 'pending'" color="orange">待解析</a-tag>
                                    <a-tag v-else-if="document.parsing_status === 'processing'" color="blue">解析中</a-tag>
                                    <a-tag v-else-if="document.parsing_status === 'completed'"
                                        color="green">解析成功</a-tag>
                                    <a-tag v-else color="red">解析失败</a-tag>
                                </a-descriptions-item>
                                <a-descriptions-item label="总结状态">
                                    <a-tag v-if="document.summary_status === 'pending'" color="orange">待总结</a-tag>
                                    <a-tag v-else-if="document.summary_status === 'processing'" color="blue">总结中</a-tag>
                                    <a-tag v-else-if="document.summary_status === 'completed'" color="green">已完成</a-tag>
                                    <a-tag v-else-if="document.summary_status === 'failed'" color="red">总结失败</a-tag>
                                    <a-tag v-else color="default">未总结</a-tag>
                                </a-descriptions-item>
                                <a-descriptions-item label="创建时间">{{ formatDateTime(document.created_at)
                                }}</a-descriptions-item>
                                <a-descriptions-item label="更新时间">{{ formatDateTime(document.updated_at)
                                }}</a-descriptions-item>
                            </a-descriptions>
                            <div class="action-buttons">
                                <a-button type="primary" v-if="document.file_url" class="full-width-btn"
                                    @click="openFile">
                                    查看原始文件
                                </a-button>
                            </div>
                        </div>
                        <a-empty v-else description="无报告信息" />

                        <a-space>
                            <a-button type="primary"
                                v-if="document?.parsing_status === 'completed' && document?.summary_status !== 'completed'"
                                :loading="summarizing" @click="handleSummarize">总结报告</a-button>
                            <a-button type="primary" v-if="document?.parsing_status !== 'completed'" :loading="parsing"
                                @click="handleParse">解析报告</a-button>
                        </a-space>
                    </a-card>
                </a-col>

                <!-- 右侧：报告内容和摘要 -->
                <a-col :span="16">
                    <ReportContent :detectionReport="document" />
                </a-col>
            </a-row>
        </a-spin>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { getDetectionReport, parseDetectionReport, summarizeDetectionReport } from '@/api/documents'
import type { DetectionReport } from '@/api/documents'
import MarkdownIt from 'markdown-it'
import ReportContent from '@/components/ReportContent.vue'

const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    breaks: true
})

const route = useRoute()
const router = useRouter()
const document = ref<DetectionReport | null>(null)
const loading = ref<boolean>(false)
const parsing = ref<boolean>(false)
const summarizing = ref<boolean>(false)
const activeTab = ref<string>('summary')

// Markdown渲染函数
const renderMarkdown = (content: string): string => {
    if (!content) return ''
    return md.render(content)
}

// 格式化日期时间函数
const formatDateTime = (dateTimeStr: string): string => {
    if (!dateTimeStr) return '';
    try {
        const date = new Date(dateTimeStr);
        return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateTimeStr;
    }
}

// 补零函数
const padZero = (num: number): string => {
    return num < 10 ? `0${num}` : `${num}`;
}

// 获取报告详情
const fetchDocument = async () => {
    const id = Number(route.params.id)
    if (!id) {
        message.error('无效的报告ID')
        return
    }

    loading.value = true
    try {
        const response = await getDetectionReport(id)
        document.value = response
        // 如果有摘要，默认显示摘要，否则显示内容
        if (response.summary) {
            activeTab.value = 'summary'
        } else if (response.html || response.text) {
            activeTab.value = 'content'
        }
    } catch (error) {
        console.error('获取报告详情失败:', error)
        message.error('获取报告详情失败')
    } finally {
        loading.value = false
    }
}

// 返回列表
const goBack = () => {
    router.push('/dashboard/report-list')
}

// 解析报告
const handleParse = async () => {
    if (!document.value) return

    parsing.value = true
    try {
        const response = await parseDetectionReport(document.value.id)
        if (response.success) {
            message.success(response.message || '报告解析已启动')
            // 重新获取文档信息
            fetchDocument()
        } else {
            message.error(response.message || '解析启动失败')
        }
    } catch (error: any) {
        console.error('解析报告失败:', error)
        message.error(error.response?.data?.error || '解析报告失败')
    } finally {
        parsing.value = false
    }
}

// 总结报告
const handleSummarize = async () => {
    if (!document.value) return

    summarizing.value = true
    try {
        const response = await summarizeDetectionReport(document.value.id)
        if (response.success) {
            message.success(response.message || '报告总结已启动')
            // 重新获取文档信息
            fetchDocument()
        } else {
            message.error(response.message || '总结启动失败')
        }
    } catch (error: any) {
        console.error('总结报告失败:', error)
        message.error(error.response?.data?.error || '总结报告失败')
    } finally {
        summarizing.value = false
    }
}

// 打开原始文件
const openFile = () => {
    if (document.value?.file_url) {
        window.open(document.value.file_url, '_blank')
    } else {
        message.warning('无法打开文件，文件链接不存在')
    }
}

onMounted(() => {
    fetchDocument()
})
</script>

<style scoped>
.report-detail {
    /*padding: 24px;*/
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
}

.cover-container {
    text-align: center;
    margin-bottom: 20px;
}

.cover-image {
    max-width: 100%;
    max-height: 300px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.summary-content,
.report-content {
    padding: 12px;
    background-color: #fff;
    overflow-y: auto;
    max-height: 600px;
    border-radius: 4px;
}

.report-content pre {
    white-space: pre-wrap;
    word-wrap: break-word;
}

.action-buttons {
    margin-top: 16px;
}

.full-width-btn {
    width: 100%;
    margin-bottom: 8px;
}

/* Markdown样式 */
.markdown-content {
    line-height: 1.6;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
}

.markdown-content h1 {
    font-size: 2em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
}

.markdown-content h2 {
    font-size: 1.5em;
    border-bottom: 1px solid #eaecef;
    padding-bottom: 0.3em;
}

.markdown-content h3 {
    font-size: 1.25em;
}

.markdown-content h4 {
    font-size: 1em;
}

.markdown-content p {
    margin-top: 0;
    margin-bottom: 16px;
}

.markdown-content blockquote {
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
    margin: 0 0 16px 0;
}

.markdown-content ul,
.markdown-content ol {
    padding-left: 2em;
    margin-bottom: 16px;
}

.markdown-content code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(27, 31, 35, 0.05);
    border-radius: 3px;
    font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}

.markdown-content pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: #f6f8fa;
    border-radius: 3px;
}

.markdown-content pre code {
    background-color: transparent;
    padding: 0;
}

.markdown-content table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 16px;
}

.markdown-content table th,
.markdown-content table td {
    padding: 6px 13px;
    border: 1px solid #dfe2e5;
}

.markdown-content table tr {
    background-color: #fff;
    border-top: 1px solid #c6cbd1;
}

.markdown-content table tr:nth-child(2n) {
    background-color: #f6f8fa;
}

.chat-container {
    display: flex;
    flex-direction: column;
    height: 600px;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background-color: #f5f5f5;
    border-radius: 4px;
    margin-bottom: 16px;
}

.message {
    margin-bottom: 16px;
}

.message-content {
    display: flex;
    align-items: flex-start;
    gap: 8px;
}

.message-avatar {
    flex-shrink: 0;
}

.message-text {
    flex: 1;
    padding: 12px;
    border-radius: 8px;
    max-width: 80%;
}

.user-message .message-content {
    flex-direction: row-reverse;
}

.user-message .message-text {
    background-color: #1890ff;
    color: white;
}

.assistant-message .message-text {
    background-color: white;
}

.message-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    text-align: right;
}

.faq-container {
    margin-bottom: 16px;
}

.faq-title {
    font-weight: 500;
    margin-bottom: 8px;
}

.faq-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.faq-tag {
    cursor: pointer;
}

.input-container {
    padding: 16px;
    background-color: white;
    border-top: 1px solid #f0f0f0;
}
</style>